package com.example.yichuangyun.ui.activity.business;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import com.example.yichuangyun.R;
import com.example.yichuangyun.config.Constant;
import com.example.yichuangyun.databinding.ActivitySearchBinding;
import com.example.yichuangyun.dialog.EditDialog;
import com.example.yichuangyun.dialog.ExamineDialog;
import com.example.yichuangyun.dialog.MyDialog;
import com.example.yichuangyun.dialog.SinglePickerView;
import com.example.yichuangyun.http.HttpRespond;
import com.example.yichuangyun.http.MyObserver;
import com.example.yichuangyun.http.RetrofitHelper;
import com.example.yichuangyun.model.business.BusinessDataModel;
import com.example.yichuangyun.model.business.BusinessModel;
import com.example.yichuangyun.mvvm.base.BaseActivity;
import com.example.yichuangyun.mvvm.base.BaseViewModel;
import com.example.yichuangyun.mvvm.ui.activity.order.PlaceOrderActivity;
import com.example.yichuangyun.ui.adapter.BusinessAdapter;
import com.example.yichuangyun.utils.CommonUtil;
import com.example.yichuangyun.utils.DensityUtil;
import com.example.yichuangyun.utils.JumpIntent;
import com.example.yichuangyun.utils.RequestUtils;
import com.example.yichuangyun.utils.ToastHelper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 搜索商机
 */
public class SearchBusinessActivity extends BaseActivity<ActivitySearchBinding, BaseViewModel> {

    private int page = 1;
    private List<BusinessModel> businessData = new ArrayList<>();
    private BusinessAdapter businessAdapter;
    /**
     * 商机类型：0-我创建的  1-部门创建的 2-我跟进的 3-部门跟进的 4-共享给我的 5-共享给部门的
     */
    private int businessType = 0;
    /**
     * 商机状态（100:全部；10:新入库；20:需跟踪；30:确认意向；40:邀约成功；50:面谈成功；60:签约成功；70:丢单；90:未签约）
     */
    private int stepStatus = 90;
    /**
     * 拨打的电话号码
     */
    private String mTelNumber;
    private String businessId;
    private String clientName;
    private MyDialog myDialog;

    private BusinessModel mBusinessModel;
    private EditDialog editDialog;
    private boolean isLostOrder;

    @Override
    protected BaseViewModel bindModel() {
        return getViewModel(this, BaseViewModel.class);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void initData() {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) binding.smartRefreshLayout.getLayoutParams();
        lp.topMargin = DensityUtil.dip2px(context, 10);
        binding.smartRefreshLayout.setLayoutParams(lp);
        binding.etSearchContent.setHint(getString(R.string.search_my_business));
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            businessType = bundle.getInt(Constant.businessTypeKey);
            stepStatus = bundle.getInt(Constant.businessStepStatusKey, 90);
        }
        initDialog();
    }

    /**
     * 获取商机列表
     */
    private void getBusinessList(int page, String content) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("keywords", content);
            requestDate.put("examine", businessType);
            requestDate.put("site", 0);
            requestDate.put("isSync", 1);
            requestDate.put("stepStatus", stepStatus);
            requestDate.put("page", page);
            requestDate.put("pageSize", Constant.pageSize);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());

        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().getBusinessList(requestBody), new MyObserver<HttpRespond<BusinessDataModel>>() {
            @SuppressLint("SetTextI18n")
            @Override
            protected void onSuccess(HttpRespond<BusinessDataModel> businessDataModelHttpRespond) {
                if (businessDataModelHttpRespond.code == Constant.SUCCESS) {
                    if (businessDataModelHttpRespond.data.getTotal() > 0) {
                        binding.llCount.setVisibility(View.VISIBLE);
                        binding.tvCount.setText(String.valueOf(businessDataModelHttpRespond.data.getTotal()));
                        binding.tvText.setText(getString(R.string.search_business_count));
                    } else {
                        binding.llCount.setVisibility(View.GONE);
                    }
                    if (businessDataModelHttpRespond.data != null && businessDataModelHttpRespond.data.getRecords() != null) {
                        List<BusinessModel> list = businessDataModelHttpRespond.data.getRecords();
                        if (list.size() < Constant.pageSize) {
                            binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                        }
                        if (page == 1) {
                            businessData = list;
                            businessAdapter.onRefresh(list);
                            binding.smartRefreshLayout.finishRefresh();
                        } else {
                            businessAdapter.addData(list);
                            binding.smartRefreshLayout.finishLoadMore();
                        }
                    }
                }
            }
        });
    }

    @Override
    public void initCtrl() {
        businessAdapter = new BusinessAdapter(context, businessData);
        binding.recyclerView.setAdapter(businessAdapter);
    }

    @Override
    protected void initClick() {
        binding.tvCancel.setOnClickListener(v -> finish());
        binding.etSearchContent.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                String content = binding.etSearchContent.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    CommonUtil.closeKeyboard(SearchBusinessActivity.this);
                    page = 1;
                    binding.recyclerView.scrollToPosition(0);
                    binding.smartRefreshLayout.autoRefresh();
                } else {
                    binding.llCount.setVisibility(View.GONE);
                    businessData.clear();
                    businessAdapter.onRefresh(businessData);
                    ToastHelper.show(getString(R.string.please_follow_search_keywords));
                }
                return true;
            }
            return false;
        });

        binding.smartRefreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (!TextUtils.isEmpty(binding.etSearchContent.getText())) {
                    page++;
                    getBusinessList(page, binding.etSearchContent.getText().toString());
                } else {
                    binding.smartRefreshLayout.finishLoadMoreWithNoMoreData();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (!TextUtils.isEmpty(binding.etSearchContent.getText())) {
                    page = 1;
                    getBusinessList(page, binding.etSearchContent.getText().toString());
                } else {
                    binding.smartRefreshLayout.finishRefresh();
                }
            }
        });

        businessAdapter.setOnCallListener((telList, id, userName) -> {
            CommonUtil.closeKeyboard(SearchBusinessActivity.this);
            businessId = id;
            clientName = userName;
            if (telList.size() > 1) {
                initSinglePickerView(telList, getString(R.string.call_num));
            } else if (telList.size() == 1) {
                mTelNumber = telList.get(0);
                RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, true);
            }
        });

        businessAdapter.setOnMoreListener((businessModel, titleData) -> {
            mBusinessModel = businessModel;
            initSinglePickerView(titleData, "");
        });
    }

    private void initDialog() {
        myDialog = new MyDialog(this) {
            @Override
            public void leftClick() {
                RequestUtils.callNum(context, mTelNumber);
                RequestUtils.addFollow(businessId, clientName, mTelNumber);
                Constant.pushBusinessId = businessId;
            }

            @Override
            public void rightClick() {
                RequestUtils.callbackOutbound(context, mTelNumber, businessId, clientName);
            }
        };

        editDialog = new EditDialog(this) {
            @Override
            public void rightClick(String content) {
                if (isLostOrder) { // 丢单
                    JSONObject requestDate = new JSONObject();
                    try {
                        requestDate.put("chanceId", mBusinessModel.getId());
                        requestDate.put("lostRemark", content);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
                    RetrofitHelper.getInstance().execute(RetrofitHelper.getService().lostOrder(requestBody), new MyObserver<HttpRespond<String>>() {
                        @Override
                        protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                            if (stringHttpRespond.code == Constant.SUCCESS) {
                                ToastHelper.show(getString(R.string.lost_order_success));
                                page = 1;
                                getBusinessList(page, binding.etSearchContent.getText().toString());
                            } else {
                                ToastHelper.show(stringHttpRespond.msg);
                            }

                        }
                    });
                } else { // 废弃
                    Map<String, Object> map = new HashMap<>();
                    map.put("attachments", new JsonArray());
                    map.put("chanceId", mBusinessModel.getId());
                    map.put("remark", content);
                    map.put("discardType", 0);
                    map.put("isDept", 0);
                    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
                    RetrofitHelper.getInstance().execute(RetrofitHelper.getService().discardBusiness(requestBody), new MyObserver<HttpRespond<String>>() {
                        @Override
                        protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                            if (stringHttpRespond.code == Constant.SUCCESS) {
                                ToastHelper.show(getString(R.string.discard_success));
                                page = 1;
                                getBusinessList(page, binding.etSearchContent.getText().toString());
                            } else {
                                ToastHelper.show(stringHttpRespond.msg);
                            }
                        }
                    });
                }
            }
        };
    }

    private void initSinglePickerView(List<String> data, String title) {
        SinglePickerView singlePickerView = new SinglePickerView(this, title, data) {
            @Override
            public void confirm(String label, int position) {
                if (title.equals(context.getString(R.string.call_num))) {
                    mTelNumber = label;
                    RequestUtils.checkCallNum(context, mTelNumber, myDialog, 0, true);
                } else {
                    if (label.equals(getString(R.string.create_order))) { // 生成订单
                        Bundle bundle = new Bundle();
                        bundle.putString(Constant.idKey, mBusinessModel.getId());
                        JumpIntent.jump(SearchBusinessActivity.this, PlaceOrderActivity.class, bundle);
                    } else if (label.equals(getString(R.string.lost_order))) { // 丢单
                        checkButtonOrTab(7);
                    } else if (label.equals(getString(R.string.discard))) { // 废弃
                        isLostOrder = false;
                        editDialog.setContent(getString(R.string.discard_reason), getString(R.string.input_discard_reason));
                        editDialog.showDialog();
                    } else if (label.equals(getString(R.string.discard_examine))) { // 废弃审核
                        discardExamineBusiness();
                    }  else {
                        checkButtonOrTab(6);
                    }
                }
            }
        };
        singlePickerView.showSinglePickerView();
    }

    /**
     * 废弃审核
     */
    private void discardExamineBusiness() {
        ExamineDialog examineDialog = new ExamineDialog(context) {
            @Override
            public void rightClick(String content, int result) {
                Map<String, Object> map = new HashMap<>();
                map.put("chanceId", mBusinessModel.getId());
                map.put("remark", content);
                map.put("type", result); // 0同意、1拒绝
                RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new Gson().toJson(map));
                RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkDiscardBusiness(requestBody), new MyObserver<HttpRespond<String>>() {
                    @Override
                    protected void onSuccess(HttpRespond<String> stringHttpRespond) {
                        if (stringHttpRespond.code == Constant.SUCCESS) {
                            ToastHelper.show(getString(R.string.discard_examine_success));
                            page = 1;
                            getBusinessList(page, binding.etSearchContent.getText().toString());
                        } else {
                            ToastHelper.show(stringHttpRespond.msg);
                        }
                    }
                });
            }
        };
        examineDialog.showDialog();
    }

    /**
     * 检测是否有按钮权限
     *
     * @param type 1、跟进记录 2、通话记录 3、订单记录 4、添加跟进 5、编辑信息 6、设置共享人 7、丢单 8、商机详情
     */
    private void checkButtonOrTab(int type) {
        JSONObject requestDate = new JSONObject();
        try {
            requestDate.put("type", type);
            // 商机类型  0、我创建的 1、部门创建的 2、我跟进的 3、部门跟进的 4、共享给我的 5、共享给部门的
            if (businessType == 0) {
                requestDate.put("businessType", mBusinessModel.getCreateUserId().equals(mBusinessModel.getGdUserId()) ? 2 : businessType);
            } else if (businessType == 1) {
                requestDate.put("businessType", mBusinessModel.getCreateUserId().equals(mBusinessModel.getGdUserId()) ? 3 : businessType);
            } else {
                requestDate.put("businessType", businessType);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), requestDate.toString());
        RetrofitHelper.getInstance().execute(RetrofitHelper.getService().checkButtonOrTab(requestBody), new MyObserver<HttpRespond<Boolean>>() {
            @Override
            protected void onSuccess(HttpRespond<Boolean> booleanHttpRespond) {
                if (Constant.SUCCESS == booleanHttpRespond.code) {
                    switch (type) {
                        case 6:
                            if (booleanHttpRespond.data) {
                                Bundle bundle = new Bundle();
                                bundle.putString(Constant.businessIdKey, mBusinessModel.getId());
                                JumpIntent.jump(SearchBusinessActivity.this, SetSharePersonActivity.class, bundle);
                            } else {
                                ToastHelper.show(getString(R.string.no_set_share_permission));
                            }
                            break;
                        case 7:
                            if (booleanHttpRespond.data) {
                                isLostOrder = true;
                                editDialog.setContent(getString(R.string.reason_for_losing_order), getString(R.string.input_reason_for_losing_order));
                                editDialog.showDialog();
                            } else {
                                ToastHelper.show(getString(R.string.no_lost_order_permission));
                            }
                            break;
                    }
                }
            }
        });
    }

}